﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace SFast.DB.Page
{

    /// <summary>
    /// 分页所必备的参数
    /// </summary>
    public class PagerOption
    {
        public static readonly PagerOption Default = new PagerOption();

        /// <summary>
        /// //获取或设置分页页码列表中,当前页左右填充显示左右邻页码数量
        /// </summary>
        public int Padding = 2;

        /// <summary>
        /// 是否显示最条数
        /// </summary>
        public bool ShowCountStr = true;   

        /// <summary>
        /// 是否显示跳转
        /// </summary>
        public bool ShowJump = true;       

        /// <summary>
        /// “上一页”按钮文本
        /// </summary>
        public string PreviousCaption = "上一页";

        /// <summary>
        /// “下一页” 按钮文本
        /// </summary>
        public string NextCaption = "下一页 ";

        /// <summary>
        /// “共 10 条” 文本
        /// </summary>
        public string RowCountFormat = "(共 {0} 条)";

        /// <summary>
        /// "转到{0}页" 文本
        /// </summary>
        public string GotoPageCaption = "转到{0}页 ";

        /// <summary>
        /// 跳转按钮文本
        /// </summary>
        public string GotoCaption = "Go";

    }

    public class TencentPage
    {
        public IPagination dataSource;
        public PagerOption Option;

        private static int GetPageIndex()
        {
            var strPage = HttpContext.Current.Request.QueryString["page"];
            if (string.IsNullOrEmpty(strPage))
                return 0;

            var pageIndex = Convert.ToInt32(strPage.Replace(",", "").Replace("&", "").Replace("?", "")) - 1;
            return pageIndex < 0 ? 0 : pageIndex;
        }


        #region 返回分页列表的html代码
        /// <summary>
        /// 返回分页列表的html代码
        /// (2011.8.23日修改,反回分页字符串,放入css样式为(.common_pagebody)容器中,并结合pageUI才可得到效果)
        /// (2011.12.9日修改，返css样式为(.common_pagebody)容器封装到代码中)
        /// </summary>
        /// <returns>分页码字符串</returns>
        public string Build()
        {
            return dataSource.PageCount > 0
                ? BuildChinesePageHtml()
                : null;
        }



        private string BuildChinesePageHtml()
        {
            var currentPageIndex = dataSource.PageNumber;//从1开始
            var pageCount = dataSource.PageCount;
            var rowCount = dataSource.RowCount;

            StringBuilder temp = new StringBuilder(1024);
            temp.Append("<link href='/Plugin/PageUI/page.css' rel='stylesheet' type='text/css' />");
            temp.Append("<div class='common_pagebody'>");
            int ShowSize = Option.Padding;  //控制分页,当前页两边显示多少个页码,其它用省略号代替 例如 : 当前页为8时 1...5 6 7 8 9 10 11...30   8左边显示3个右边显示3个   

            #region 上一页 和 设置第一页
            if (currentPageIndex > 1)
            {
                temp.Append(GetTempHtml(currentPageIndex - 1, "Previous", Option.PreviousCaption, true));           //当前页不为1的时： 上一页
                temp.Append(GetTempHtml(1, "MinPage", "1", true));                           //当前页不为1的时： 第一页
            }
            else
                temp.Append(GetTempHtml(1, "Previous Enabled", Option.PreviousCaption, false)); //当前页为第一页时不可用
            #endregion

            #region 中间部分
            if (currentPageIndex - ShowSize > 2)
            {
                temp.Append("<span class='points'>...</span>");
                for (int i = ShowSize; i > 0; i--)
                    temp.Append(GetTempHtml(currentPageIndex - i, "", (currentPageIndex - i).ToString(), true));
            }
            else
            {
                for (int i = 2; i < currentPageIndex; i++)
                    temp.Append(GetTempHtml(i, "", i.ToString(), true));
            }

            //当前页
            temp.Append(GetTempHtml(currentPageIndex, "CurrentPage", currentPageIndex.ToString(), false));


            //当前页后的页号处理
            if (currentPageIndex + ShowSize < pageCount - 1)
            {
                for (int i = 1; i < ShowSize + 1; i++)
                    temp.Append(GetTempHtml(currentPageIndex + i, "", (currentPageIndex + i).ToString(), true));
                temp.Append("<span class='points'>...</span>");
            }
            else
            {
                for (int i = currentPageIndex + 1; i < pageCount; i++)
                    temp.Append(GetTempHtml(i, "", i.ToString(), true));
            }

            #endregion

            #region 下一页  和 最后一页
            if (currentPageIndex < pageCount)
            {
                temp.Append(GetTempHtml(pageCount, "", pageCount.ToString(), true));
                temp.Append(GetTempHtml(currentPageIndex + 1, "NextPage", Option.NextCaption, true));
            }
            else
            {
                temp.Append(GetTempHtml(pageCount, "NextPage Enabled", Option.NextCaption, false));
            }
            #endregion

            #region (共 多少 条)、转到 多少 页 、跳转按钮
            if (Option.ShowCountStr)
                temp.AppendFormat("<span class='Rows_Count'>" + Option.RowCountFormat + "</span>", rowCount);
            //判断是否要显示这个跳转
            if (Option.ShowJump)
                temp.AppendFormat(" <span class='jump'>" + Option.GotoPageCaption + "</span><input class='Page_Bt_Go' type=button onclick=\"pageJump(document.getElementById('pagejump').value);\" value=" + Option.GotoCaption + " />", "<input name=page type=text id=pagejump size=3/>");
            temp.Append("<div style='clear:both'></div> </div>");
            //temp.Append(@"<script language=javascript>function pageJump(value){ var urls=location.href;var CanShuStr='';var CanShuJiHe= new Array(); if (value >" + PageCount + " || value < 1) {alert('输入有误！请输入范围为 1 ~ " + PageCount + "的数字！'); return false;}if(urls.indexOf('?')>-1){ CanShuStr=urls.split('?')[1];  if (CanShuStr.indexOf('page')>-1){ if(CanShuStr.indexOf('&')>-1){ CanShuJiHe=CanShuStr.split('&');}else{  CanShuJiHe[0]=CanShuStr;}}else{urls=urls+'&page='+value;} var x; for(x in CanShuJiHe){ var canshu=CanShuJiHe[x]; if(canshu.indexOf('page')>-1){urls=urls.replace(canshu,'page='+value);}}}else{urls=urls+'?page='+value;} if (value==1) { urls = urls.replace('?page=1&', '?').replace('?page=1', '').replace('&page=1&', '&').replace('&page=1', ''); } location.href=urls;}</script>");
            temp.Append(@"<script language=javascript> 
                                var pageJump = function(value) {
                                    var urls = location.href;
                                    var CanShuStr = '';
                                    var CanShuJiHe = new Array();
                                    var reg = /\d+/;
                                    if (reg.test(value) == false || value == '')
                                    { alert('请填写有效的数字字符！'); return false; }
");
            temp.Append("        if (value > " + pageCount + " || value < 1) {");
            temp.Append("                       alert('输入有误！请输入范围为 1 ~ " + pageCount + "的数字！'); return false;");
            temp.Append("                   }");
            temp.Append(@" if (urls.indexOf('?') > -1) {
                                        CanShuStr = urls.split('?')[1];
                                        if (CanShuStr.indexOf('page') > -1) {
                                            if (CanShuStr.indexOf('&') > -1) { CanShuJiHe = CanShuStr.split('&'); } else { CanShuJiHe[0] = CanShuStr; }
                                        } else {
                                            urls = urls + '&page=' + value;
                                        }
                                        var x;
                                        for (x in CanShuJiHe) {
                                            var canshu = CanShuJiHe[x];
                                            if (canshu.indexOf('page') > -1) {
                                                urls = urls.replace(canshu, 'page=' + value);
                                            }
                                        }
                                    } else {
                                        urls = urls + '?page=' + value;
                                    }
                                    if (value == 1) {
                                        urls = urls.replace('?page=1&', '?').replace('?page=1', '').replace('&page=1&', '&').replace('&page=1', '');
                                    }
                                    location.href = urls;
                                } 
                            </script>");
            #endregion

            return temp.ToString();
        }
        #endregion

        #region 给现有的url加入或修改页码，返回url
        /// <summary>
        /// 通过分页模板拼出单个分页的代码
        /// </summary>
        /// <param name="pageid">页码</param>
        /// <param name="css">CssClass</param>
        /// <param name="ShowText">显示文本</param>
        /// <returns></returns>
        private string GetTempHtml(int pageid, String css, String ShowText, bool IsEnabled)
        {
            const String PageUrlTemp = "<a class='{0}' href=\"{1}\"><span>{2}</span></a> ";                           //URL显示分页模板

            string url = HttpContext.Current != null
                ? HttpContext.Current.Request.Url.PathAndQuery
                : "";      //获取当前页的url地址
            String newurl = IsEnabled
                ? this.GetPagedUrl(url, pageid)
                : "javascript:void(0);";

            return String.Format(PageUrlTemp, css, newurl, ShowText);         //生成完整的url分页代码
        }
        #endregion

        #region 给现有的url加入或修改页码，返回url
        /// <summary>
        /// 给现有的url加入或修改页码，返回url
        /// </summary>
        /// <param name="url"> 当前页的url </param>
        /// <param name="pageid"> 页面ID </param>
        /// <returns></returns>
        private string GetPagedUrl(string url, int pageid)
        {
            url = url.ToLower();
            if (pageid == 1)
                url = Regex.Replace(url, "page=[0-9]*", "");
            else
            {
                if (Regex.Match(url, "page=[0-9]*").Success)
                    url = Regex.Replace(url, "page=[0-9]*", "page=" + pageid.ToString());
                else
                {
                    if (url.IndexOf("?") == -1)
                        url += "?page=" + pageid.ToString();
                    else
                        url += "&page=" + pageid.ToString();
                }
            }
            url = url.Replace("&&", "&").Replace("?&", "?");
            if (url.Split('?').Length > 1 && String.IsNullOrEmpty(url.Split('?')[1]))
                url = url.Replace("?", "");
            return url.ToLower();
        }
        #endregion
    }
}
